<template>
  <div class="left" ref="leftRef">
    <div class="left-content">
      <!--      <div class="left-content-tag-t" />-->
      <!--      <div class="left-content-tag-b" />-->
      <div class="panel-title">
        <img :src="TitleIcon" />
        <span>项目列表</span>
      </div>
      <div class="investPro-title">
        <div
          @click="toolItemClickHandle(item)"
          v-for="(item, index) in toolData"
          :key="index"
          :class="{
            'is-active': activeTool === item.value
          }"
        >
          {{ item.label }}
          <p class="line"></p>
        </div>
      </div>
      <div class="left-content-search">
        <Search
          v-model="keyword"
          placeholder="请输入关键词"
        />
      </div>
      <el-scrollbar class="left-content-tree">
        <div v-show="activeTool === 'government'">
          <div class="project-list">
            <div
              class="project-list-item"
              v-for="data in shownProjectListData"
              :key="data.pkid"
            >
              <div class="project-list-item-top">
                <div class="project-list-item-top__title">
                  <span class="name">{{
                    data.项目名称
                  }}</span>
                  <span
                    style="
                      color: #0098ff;
                      margin-right: 6px;
                      font-weight: 600;
                      font-size: 16px;
                    "
                    >{{ data.建设周期 || '' }}</span
                  >
                  <span
                    class="status"
                    :class="{
                      zj: data.项目阶段 === '前期',
                      jc: data.项目阶段 === '新建',
                      dj: data.项目阶段 === '续建'
                    }"
                    >{{ data.项目阶段 }}</span
                  >
                </div>
              </div>
              <div class="project-list-item-bottom">
                <span
                  >{{ data.totalPrice || '--' }}万元</span
                >
                <span>{{ data.项目进度 || '--' }}</span>
                <span
                  >年度目标：{{
                    data.年度目标 || '--'
                  }}</span
                >
              </div>
            </div>
          </div>
        </div>
        <div v-show="activeTool === 'enterprise'">
          <div class="project-list">
            <div
              class="project-list-item"
              v-for="data in shownProjectListData"
              :key="data.pkid"
            >
              <div class="project-list-item-top">
                <div class="project-list-item-top__title">
                  <span class="name">{{
                    data.项目名称
                  }}</span>
                  <span class="year">{{
                    data.建设周期 || ''
                  }}</span>
                  <span class="type">企业类型</span>
                </div>
              </div>
              <div class="project-list-item-bottom">
                <span
                  >{{ data.totalPrice || '--' }}万元</span
                >
                <span>{{ data.项目阶段 }}续</span>
                <span
                  >年度目标：{{
                    data.年度目标 || '--'
                  }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import TitleIcon from '@/assets/img/logo.png'
import axios from 'axios'
import Search from '@/components/search'
import { getAction } from '@/utils/helper'
import { retrieveDataServiceById } from '@/api/multiple-dataservice'
import { treeBySpecialType } from '@/api/tree'
import New from '@/utils/new'

export default {
  name: 'ProjectPanelRight',
  components: {
    Search
  },
  data() {
    return {
      TitleIcon,
      keyword: '',
      pageSize: 100,
      pageIndex: 1,
      projectListData: [],
      shownProjectListData: [],
      toolData: [
        {
          label: '政府投资项目',
          value: 'government'
        },
        {
          label: '企业投资项目',
          value: 'enterprise'
        }
      ],
      activeTool: 'government',
      propertyList: '',
      projectUrl: '',
      mapProjectList: [],
      mapProjectListData: []
    }
  },
  async created() {
    this.getTree()

    const { viewer } = await getAction(this.defaultViewId)
    mapViewer[this.defaultViewId] = viewer
  },
  mounted() {
    New.$on('leftTabChange', (data) => {
      switch (data) {
        case 'government':
          this.activeTool = 'government'
          break
        case 'enterprise':
          this.activeTool = 'enterprise'
          break
        default:
          break
      }
      this.getTree()
    })
  },
  beforeDestroy() {
    New.$off('leftTabChange')
  },
  methods: {
    getTree() {
      treeBySpecialType('shengzhangdongtai').then((res) => {
        const list = res.data[0].children
        if (this.activeTool === 'government') {
          this.getLayer(
            list[0].resourceInfo
              ? list[0].resourceInfo[0]
              : null
          )
        } else if (this.activeTool === 'enterprise') {
          this.getLayer(
            list[1].resourceInfo
              ? list[1].resourceInfo[0]
              : null
          )
        }
      })
    },
    async getLayer(item) {
      if (!item) {
        return
      }
      const dataList = await this.getDataList(item.pkid)
      item.dataList = dataList
      item.serviceUrl = item.dataList[0].serviceUrl
      item.signService = item.dataList[0].signService
      item.currentDataIndex = 0
      this.projectUrl =
        item.dataList[
          item.currentDataIndex
        ].resourceServiceDataInfoList[0].serviceDataUrl
      this.getFieldList(this.projectUrl)
    },
    // 获取服务的地图服务列表
    async getDataList(pkid) {
      const list = []
      await retrieveDataServiceById({
        pageIndex: 1,
        pageSize: 999,
        serviceId: pkid
      }).then((res) => {
        if (res.success) {
          if (res.data && res.data.length) {
            // 将配置的数据列表赋给原始数据
            list.push(...res.data)
          } else {
            this.$message.warning('该服务未配置数据')
          }
        } else {
          this.$message.error(
            res.message || '服务数据查询失败'
          )
        }
      })
      return list
    },
    getFieldList(url) {
      axios.get(`${url}/fields.json`).then((res) => {
        if (res.data) {
          this.propertyList = res.data.fieldNames
          this.getProjectInfoList(url)
        }
      })
    },
    getProjectInfoList(url) {
      const dataService = decodeURI(url)
      const dataServiceUrl =
        dataService.substring(
          0,
          dataService.lastIndexOf('/datasources/')
        ) +
        '/featureResults.json?returnContent=true&toIndex=-1'
      const dataSourceAndDataSet = dataService
        .substring(
          dataService.lastIndexOf('/datasources/') +
            '/datasources/'.length
        )
        .split('/datasets/')
        .map((item) => decodeURI(item))
      const str = []
      if (this.projectCycle) {
        str.push(`计划年度 = '${this.projectCycle}'`)
      }
      if (this.projectStage) {
        str.push(`项目阶段 = '${this.projectStage}'`)
      }
      if (this.projectStatus) {
        str.push(`项目状态 = '${this.projectStatus}'`)
      }
      if (this.projectType) {
        str.push(`项目类型 = '${this.projectType}'`)
      }
      if (this.projectArea) {
        str.push(`项目片区 = '${this.projectArea}'`)
      }
      if (this.projectProgress) {
        str.push(`项目进度 = '${this.projectProgress}'`)
      }
      const sqlParameter = {
        datasetNames: [`${dataSourceAndDataSet.join(':')}`],
        getFeatureMode: 'SQL',
        queryParameter: {
          fields: this.propertyList,
          attributeFilter: str.length
            ? str.join(' AND ')
            : ''
          // groupBy: `${val.label}`
        }
      }
      this.projectListData = []
      this.shownProjectListData = []
      const queryData = JSON.stringify(sqlParameter)
      axios.post(dataServiceUrl, queryData).then((res) => {
        if (res.data.featureCount > 0) {
          const list = res.data.features
          const dataList = []
          const leftDataList = []
          list.forEach((i) => {
            const leftData = {}
            const fieldValues = i.fieldValues
            const fieldNames = i.fieldNames

            // const projectCycleIndex = fieldNames.findIndex(
            //   (item) => item === '计划年度'
            // )
            // const projectStageIndex = fieldNames.findIndex(
            //   (item) => item === '项目阶段'
            // )
            const projectStatusIndex = fieldNames.findIndex(
              (item) => item === '项目状态'
            )
            const projectTypeIndex = fieldNames.findIndex(
              (item) => item === '项目类型'
            )
            const projectAreaIndex = fieldNames.findIndex(
              (item) => item === '项目片区'
            )
            // const projectProgressIndex =
            //   fieldNames.findIndex(
            //     (item) => item === '项目进度'
            //   )
            if (projectStatusIndex !== -1) {
              if (fieldValues[projectStatusIndex]) {
                leftData.projectStatus =
                  fieldValues[projectStatusIndex]
              }
            }
            if (projectTypeIndex !== -1) {
              if (fieldValues[projectTypeIndex]) {
                leftData.projectType =
                  fieldValues[projectTypeIndex]
              }
            }
            if (projectAreaIndex !== -1) {
              if (fieldValues[projectAreaIndex]) {
                leftData.projectArea =
                  fieldValues[projectAreaIndex]
              }
            }

            const va = {}
            fieldValues.forEach((value, idx) => {
              if (fieldNames[idx] === '项目投资（万元）') {
                if (value) {
                  leftData.projectValue = value
                }
                fieldNames[idx] = 'totalPrice'
              }
              if (
                fieldNames[idx] === '计划完成投资（万元）'
              ) {
                fieldNames[idx] = 'planPrice'
              }
              va[fieldNames[idx]] = value
            })
            const list = []
            i.geometry.points.map((item) => {
              list.push([item.x, item.y])
            })
            va.geometry = i.geometry
            dataList.push(va)
            leftDataList.push(leftData)
          })
          New.$emit('getProjectInfo', leftDataList)
          this.projectListData = dataList
          this.shownProjectListData = dataList
        }
      })
    },

    toolItemClickHandle(data) {
      const { value } = data
      this.activeTool =
        this.activeTool === value ? undefined : value
      if (this.activeTool) {
        New.$emit('rightTabChange', this.activeTool)
      }
      this.getTree()
    }
  },
  watch: {
    keyword(val) {
      if (val) {
        this.shownProjectListData =
          this.projectListData.filter((item) => {
            return (
              item.项目名称 &&
              item.项目名称.indexOf(val) !== -1
            )
          })
      } else {
        this.shownProjectListData = this.projectListData
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.left {
  width: 100%;
  height: 100%;
  background-color: rgba(7, 13, 35, 0.5);
  padding: 20px 0 20px 20px;

  &-content {
    width: 100%;
    height: 100%;
    overflow: hidden;
    //padding: 10px 0;
    position: relative;

    .panel-title {
      margin-bottom: 20px;
      display: flex;
      align-items: center;

      img {
        width: 34px;
        height: 34px;
      }

      span {
        margin-left: 20px;
        font-size: 24px;
        color: white;
        font-weight: 800;
      }
    }

    &-tag {
      &-t {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 5px;

        &::before,
        &::after {
          content: '';
          width: 0;
          height: 0;
          position: absolute;
          top: 0;
        }

        &::before {
          left: 0;
          border-top: 4px solid #fff;
          border-right: 4px solid transparent;
        }

        &::after {
          right: 0;
          border-top: 4px solid #fff;
          border-left: 4px solid transparent;
        }
      }

      &-b {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 5px;

        &::before,
        &::after {
          content: '';
          width: 0;
          height: 0;
          position: absolute;
          bottom: 0;
        }

        &::before {
          left: 0;
          border-bottom: 4px solid #fff;
          border-right: 4px solid transparent;
        }

        &::after {
          right: 0;
          border-bottom: 4px solid #fff;
          border-left: 4px solid transparent;
        }
      }
    }

    &-title {
      height: 50px;
      line-height: 50px;
      padding-left: 14px;
      font-size: 18px;
      font-weight: 800;
      color: #00d2ff;
      word-break: keep-all;
      border-top: 1px solid rgba(255, 255, 255, 0.2);
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    &-search {
      height: 30px;
      width: calc(100% - 20px);
      margin: 15px 0;
      display: flex;
      align-items: center;
    }

    &-tree {
      ::v-deep {
        .el-scrollbar__wrap {
          overflow-x: hidden;

          .project-list {
            padding-right: 20px;

            &-item {
              background-color: rgba(25, 47, 61, 0.5);
              border: 1px solid rgba(0, 0, 0, 0.2);
              margin-bottom: 4px;
              padding: 10px;

              &:hover {
                background-color: rgba(255, 255, 255, 0);
              }

              &-top {
                display: flex;
                align-items: center;

                .el-checkbox__input {
                  margin-right: 10px;

                  .el-checkbox__inner {
                    width: 12px;
                    height: 12px;
                    background: rgba(255, 255, 255, 0.3);
                    border: 1px solid #ffffff;
                  }
                }

                &__title {
                  width: 100%;
                  display: flex;
                  align-items: center;

                  .name {
                    font-size: 16px;
                    font-weight: 800;
                    flex: 1;
                    // text-overflow: ellipsis;
                    // overflow: hidden;
                    display: inline-block;
                    // white-space: nowrap;
                    margin-right: 10px;
                  }

                  .status {
                    float: right;
                    position: relative;
                    text-align: center;
                    line-height: 24px;
                    width: 44px;
                    height: 24px;
                    font-size: 16px;

                    &::before {
                      content: '';
                      width: 7px;
                      height: 7px;
                      background: rgba(0, 0, 0, 0.5);
                      position: absolute;
                      left: 0;
                      top: 0;
                      clip-path: polygon(
                        80% -1px,
                        100% 0,
                        0 100%,
                        -1px 80%
                      );
                    }

                    &::after {
                      content: '';
                      width: 7px;
                      height: 7px;
                      background: rgba(0, 0, 0, 0.5);
                      position: absolute;
                      right: 0;
                      bottom: 0;
                      clip-path: polygon(
                        100% 0,
                        100% 40%,
                        40% 100%,
                        0 100%
                      );
                    }
                  }

                  .zj {
                    background: linear-gradient(
                      270deg,
                      #cfaf00,
                      #beb683
                    );
                  }

                  .jc {
                    background: linear-gradient(
                      270deg,
                      #00b79f,
                      #8ab700
                    );
                  }

                  .dj {
                    background: linear-gradient(
                      150deg,
                      #e3a482,
                      #c45833
                    );
                  }

                  .year {
                    color: #00d2ff;
                    font-size: 16px;
                    margin-right: 10px;
                  }

                  .type {
                    width: 70px;
                    height: 24px;
                    background: #c5891a;
                    color: white;
                    font-size: 16px;
                    text-align: center;
                    line-height: 24px;
                    border-radius: 2px;
                  }
                }
              }

              &-bottom {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 9px;

                span {
                  font-size: 14px;
                  font-weight: 500;
                  color: #d2e6f0;
                }
              }
            }
          }
        }
      }

      width: 100%;
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);
      height: calc(100% - 50px - 50px - 40px);

      &-item:not(:last-child) {
        margin-bottom: 4px;
      }

      &-item {
        background: rgba(0, 0, 0, 0.2);
        padding: 10px 8px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        display: flex;
        justify-content: space-between;
        align-items: flex-start;

        &-l {
          flex: 1;
          margin-right: 10px;
          display: flex;
          flex-direction: column;

          & > span:nth-child(1) {
            word-break: break-all;
            font-size: 14px;
            font-weight: 800;
            color: #ffffff;
          }

          & > span:nth-child(2) {
            font-size: 12px;
            font-weight: 500;
            color: #d2e6f0;
          }
        }

        &-r {
          width: 40px;
          height: 20px;
          font-size: 14px;
          font-weight: 400;
          color: #ffffff;
          text-align: center;
          line-height: 20px;
          background: linear-gradient(
            270deg,
            #505fba,
            #949bc5
          );
          position: relative;

          &::before {
            content: '';
            width: 7px;
            height: 7px;
            background: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 0;
            top: 0;
            clip-path: polygon(
              80% 0,
              100% 0,
              0 100%,
              0 80%
            );
          }
        }
      }
    }
  }
}

.investPro {
  &-title {
    display: flex;
    height: 50px;
    line-height: 50px;
    cursor: pointer;

    > div {
      margin-right: 20px;
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #d2e6f0;

      &:first-child {
        margin-left: 10px;
      }
    }

    .is-active {
      color: rgba(26, 217, 255, 1);
    }
  }
}
</style>
